package com.xzz.trieTree;

import java.util.Arrays;
import java.util.List;

/**
 * @author: hhz
 * @create: 2022-01-20 11:14
 * 648. 单词替换
 **/
public class ReplaceWords {
    public static void main(String[] args) {
        System.out.println(replaceWords(Arrays.asList("cat","bat","rat"),"the cattle was rattled by the battery"));
        System.out.println(replaceWords(Arrays.asList("a","b","c"),"aadsfasf absbs bbab cadsfafs"));
    }
    public static String replaceWords(List<String> dictionary, String sentence) {
        TrieSet trieSet = new TrieSet();
        for (String s : dictionary) {
            trieSet.add(s);
        }
        StringBuilder sb = new StringBuilder();
        String[] s = sentence.split(" ");
        for (int i = 0; i < s.length; i++) {
            String shortestPrefix = trieSet.shortestPrefixOf(s[i]);
            if(shortestPrefix.isEmpty()){
                sb.append(s[i]);
            }else {
                sb.append(shortestPrefix);
            }
            if (i != s.length - 1) {
                // 添加单词之间的空格
                sb.append(' ');
            }
        }
        return sb.toString();
    }
}
